/**
 * 
 */
package org.mspring.crm.client.mvc;

import java.util.Arrays;
import java.util.List;

import org.mspring.crm.client.AppEvents;
import org.mspring.crm.client.Application;
import org.mspring.crm.client.model.Entry;
import org.mspring.crm.client.model.ItemModel;
import org.mspring.crm.client.remote.ItemRemote;
import org.mspring.crm.client.widget.LoginDialog;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.data.BaseTreeLoader;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.extjs.gxt.ui.client.data.TreeLoader;
import com.extjs.gxt.ui.client.event.EventType;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.WindowEvent;
import com.extjs.gxt.ui.client.mvc.AppEvent;
import com.extjs.gxt.ui.client.mvc.Controller;
import com.extjs.gxt.ui.client.mvc.Dispatcher;
import com.extjs.gxt.ui.client.mvc.View;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HtmlContainer;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.custom.ThemeSelector;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * @author Gao Youbo
 * @since 2012-3-5
 * 
 */
public class ApplicationView extends View {

    public static final String CENTER_PANEL = "center_panel";
    public static final String LEFT_PANEL = "left_panel";
    public static final String TOP_PANEL = "top_panel";
    public static final String VIEWPORT = "viewport";

    private Viewport viewport;
    private ContentPanel centerPanel;
    private HtmlContainer topPanel;
    private ContentPanel leftPanel;

    private TreePanel<ItemModel> tree;

    /**
     * @param controller
     */
    public ApplicationView(Controller controller) {
        super(controller);
        // TODO Auto-generated constructor stub
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.extjs.gxt.ui.client.mvc.View#initialize()
     */
    @Override
    protected void initialize() {
        // TODO Auto-generated method stub
        LoginDialog dialog = new LoginDialog();
        dialog.setClosable(false);
        dialog.addListener(Events.Hide, new Listener<WindowEvent>() {
            public void handleEvent(WindowEvent be) {
                Dispatcher.forwardEvent(AppEvents.Init);
            }
        });
        dialog.show();
    }

    /*
     * (non-Javadoc)
     * 
     * @see
     * com.extjs.gxt.ui.client.mvc.View#handleEvent(com.extjs.gxt.ui.client.
     * mvc.AppEvent)
     */
    @Override
    protected void handleEvent(AppEvent event) {
        // TODO Auto-generated method stub
        EventType type = event.getType();
        if (type == AppEvents.Init) {
            initUI();
        } else if (type == AppEvents.HidePage) {
            tree.getSelectionModel().deselectAll();
        } else if (type == AppEvents.TabChange) {
            if (((Entry) event.getData()).getName() == "Overview") {
                tree.getSelectionModel().deselectAll();
            } else {
                tree.getSelectionModel().setSelection((List) Arrays.asList((Entry) event.getData()));
            }
        }
    }

    private void initUI() {
        viewport = new Viewport();
        viewport.setLayout(new BorderLayout());
        Registry.register(VIEWPORT, viewport);

        createTopPanel();
        createLeftPanel();
        createCenterPanel();

        RootPanel.get().add(viewport);
    }

    /**
     * 创建Center主页面
     */
    private void createCenterPanel() {
        centerPanel = new ContentPanel();
        centerPanel.setBorders(false);
        centerPanel.setHeaderVisible(false);
        centerPanel.setLayout(new FitLayout());

        BorderLayoutData data = new BorderLayoutData(LayoutRegion.CENTER);
        data.setMargins(new Margins(5, 5, 5, 0));
        viewport.add(centerPanel, data);
        Registry.register(CENTER_PANEL, centerPanel);
    }

    private void createLeftPanel() {
        BorderLayoutData data = new BorderLayoutData(LayoutRegion.WEST, 220, 150, 320);
        data.setMargins(new Margins(5, 5, 5, 5));
        data.setCollapsible(true);
        leftPanel = new ContentPanel();

        createTreeContent();
        viewport.add(leftPanel, data);
        Registry.register(LEFT_PANEL, leftPanel);
    }

    private void createTopPanel() {
        StringBuffer sb = new StringBuffer();
        sb.append("<div id='crm-theme'></div><div id=crm-title>M-Spring CRM</div>");

        topPanel = new HtmlContainer(sb.toString());
        topPanel.setStateful(false);
        topPanel.setId("crm-header");
        topPanel.addStyleName("x-small-editor");

        ThemeSelector selector = new ThemeSelector();
        selector.setWidth(125);
        topPanel.add(selector, "#crm-theme");

        BorderLayoutData data = new BorderLayoutData(LayoutRegion.NORTH, 33);
        data.setMargins(new Margins());
        viewport.add(topPanel, data);
        Registry.register(TOP_PANEL, topPanel);
    }

    private void createTreeContent() {
        RpcProxy<List<ItemModel>> proxy = new RpcProxy<List<ItemModel>>() {
            @Override
            protected void load(Object loadConfig, AsyncCallback<List<ItemModel>> callback) {
                // TODO Auto-generated method stub
                ItemModel model = (ItemModel) loadConfig;
                int id = 0;
                if (model != null) {
                    id = model.getId();
                }
                ItemRemote.Util.getInstance().generateTreeItem(1, id, callback);
            }
        };
        TreeLoader<ItemModel> loader = new BaseTreeLoader<ItemModel>(proxy) {
            @Override
            public boolean hasChildren(ItemModel parent) {
                return parent.getIsParent();
            }
        };
        TreeStore<ItemModel> treeStore = new TreeStore<ItemModel>(loader);
        tree = new TreePanel<ItemModel>(treeStore);
        tree.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        tree.getStyle().setLeafIcon(IconHelper.createStyle("icon-list"));
        tree.setAutoLoad(true);
        tree.setDisplayProperty("name");

        // SelectionService.get().addListener(new
        // SourceSelectionChangedListener(tree.getSelectionModel()));
        // SelectionService.get().register(tree.getSelectionModel());
        tree.getSelectionModel().addSelectionChangedListener(new SelectionChangedListener<ItemModel>() {

            @Override
            public void selectionChanged(SelectionChangedEvent<ItemModel> se) {
                // TODO Auto-generated method stub
                ItemModel item = se.getSelection().get(0);
                if (item != null && item instanceof ItemModel) {
                    Application.showPage(item);
                }
            }
        });

        leftPanel.setBorders(false);
        leftPanel.setLayout(new FitLayout());
        leftPanel.add(tree);
    }

}
